package com.lyc.attend.service.impl;

import com.lyc.attend.dao.AttendMapper;
import com.lyc.attend.entity.Attend;
import com.lyc.attend.service.IAttendService;
import com.lyc.common.constant.SignInConstant;
import com.lyc.common.page.PageQueryBean;
import com.lyc.common.page.PageQueryConditions;
import com.lyc.common.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AttendServiceImpl implements IAttendService {

    @Autowired
    private AttendMapper attendMapper;

    private Log log = LogFactory.getLog(this.getClass());

    /**
     * 业务逻辑：
     * 中午十二点之前打卡    上午打卡时间  9点以后打卡 算迟到 抛异常
     * 十二点之后打卡        晚上打卡时间  18点以前打卡 算早退 记录缺勤时长
     * 晚上打卡时检查与上午打卡时间差 不足八个小时 算早退 记录缺勤时长
     *
     * @param attend 打卡信息
     * @throws Exception
     */
    @Override
    @Transactional
    public void addAttendanceRecord(Attend attend) throws Exception {
        try {
            Date now = new Date();
            attend.setAttendDate(now);
            attend.setAttendWeek((byte) DateUtil.getWeekDay(now));
            Date noon = DateUtil.getTime(SignInConstant.NOON_HOUR, SignInConstant.SHARP_MINUTE, SignInConstant.SHARP_SECOND);
            int result = now.compareTo(noon);
            //查询用户今天打没打卡
            Attend attendanceRecord = attendMapper.selectTodayAttendanceRecord(attend.getUserId());
            if (attendanceRecord == null) {
                //不存在打卡记录，可以早上打卡
                if (result == SignInConstant.BEFORE_NOON) {
                    //早上打卡
                    attend.setAttendMorning(now);
                    Date office_time = DateUtil.getTime(SignInConstant.OFFICE_HOUR, SignInConstant.OFFICE_MINUTE, SignInConstant.SHARP_SECOND);
                    //早上打卡迟到
                    if (now.compareTo(office_time) == 1) {
                        attend.setAttendStatus(SignInConstant.ABSENCE_STATUS);
                        attend.setAbsence(DateUtil.getTimeDValue(office_time, now));
                    }
                } else if (result == SignInConstant.AFTER_NOON)
                    //早上没打卡 晚上打卡 不让打卡
                    return;
//                    attend.setAttendEvening(now);
                attendMapper.insertSelective(attend);
            } else {
                //存在打卡记录
                //早卡已打 晚卡未打 早上不让打卡
                if (result == SignInConstant.BEFORE_NOON)
                    return;
                else if (result == SignInConstant.AFTER_NOON) {
                    attendanceRecord.setAttendEvening(now);
                    Date leave_time = DateUtil.getTime(SignInConstant.LEAVE_HOUR, SignInConstant.LEAVE_MINUTE, SignInConstant.SHARP_SECOND);
                    if (now.compareTo(leave_time) == -1) {
                        //早退
                        attend.setAttendStatus(SignInConstant.ABSENCE_STATUS);
                        attendanceRecord.setAbsence(DateUtil.getTimeDValue(leave_time, now));
                    }
                }
                //更新晚上最后一次打卡的时间
                attendMapper.updateByPrimaryKeySelective(attendanceRecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //打印异常日志
            log.error("用户签到异常", e);
            //抛出异常，让事务回滚
            throw e;//注意：不抛出异常，事务无法回滚
        }
    }

    /**
     * 分页条件查询
     *
     * @param queryConditions 查询条件
     * @return 分页对象
     */
    @Override
    public PageQueryBean pageQueryByConditions(PageQueryConditions queryConditions) {
        //获取数据的总数量
        int count = attendMapper.selectPageTotalRowsByConditions(queryConditions);
        //数量大于0 有数据 查询
        if (count > 0) {
            PageQueryBean pageResult = new PageQueryBean();
            pageResult.setCurrentPage(queryConditions.getCurrentPage());
            pageResult.setPageSize(queryConditions.getPageSize());
            pageResult.setStartRow(queryConditions.getStartRow());
            pageResult.setTotalRows(count);
            List<Attend> items = attendMapper.selectByPageConditions(queryConditions);
            pageResult.setItems(items);
            return pageResult;
        }
        return null;
    }

    /**
     * 核对出勤记录
     */
    @Override
    @Transactional
    public void checkAttend() {
        try {
            //查询缺勤用户ID 插入打卡记录  并且设置为异常 缺勤480分钟
            List<Long> userIdList = attendMapper.selectWholeAbsenceRecord();
            if (CollectionUtils.isNotEmpty(userIdList)) {
                List<Attend> attendList = new ArrayList<>();
                for (Long userId : userIdList) {
                    Attend attend = new Attend();
                    attend.setUserId(userId);
                    attend.setAttendDate(new Date());
                    attend.setAttendWeek((byte) DateUtil.getWeekDay(new Date()));
                    attend.setAbsence(SignInConstant.ABSENCE_WHOLE_DAY);
                    attend.setAttendStatus(SignInConstant.ABSENCE_STATUS);
                    attendList.add(attend);
                }
                attendMapper.insertAbsenceRecord(attendList);
            }
            List<Attend> unSignInList = attendMapper.selectEveningAbsenceRecord();
            //修改晚上没打卡的出勤信息（缺勤）
            for (Attend unsigned : unSignInList) {
                unsigned.setAbsence(SignInConstant.ABSENCE_WHOLE_DAY);
                unsigned.setAttendStatus(SignInConstant.ABSENCE_STATUS);
                attendMapper.updateByPrimaryKeySelective(unsigned);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
